package cn.aylog.accountdemo.controller;

import cn.aylog.accountdemo.pojo.Account;
import cn.aylog.accountdemo.pojo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/account")
public class AccountController {

    private List<Account> list = new ArrayList<>();

    private Logger logger = LoggerFactory.getLogger(AccountController.class);

    @RequestMapping(value = "/users", method = RequestMethod.GET)
    public Result list() {
        logger.trace("method: [Result] ...");
        if(list.isEmpty()) {
            list.add(new Account(1,"tom1", "123"));
            list.add(new Account(2,"tom2", "123"));
            list.add(new Account(3,"tom3", "123"));
        }
        return new Result(200, "查询成功", list);
    }

    @RequestMapping(value = "/users", method = RequestMethod.POST)
    public Result add(List<Account> list) {
        logger.trace("method: [Result] ...");
        list.containsAll(list);
        return new Result(200, "更新成功");
    }

    @RequestMapping(value ={ "/user", "/user/{id}"}, method = RequestMethod.PUT)
    public Result update(Account account, @Nullable @PathVariable Integer id) {
        if(id != null) {
            id = account.getId();
        }
        if(id == null) {
            return new Result(201, "更新失败id不能为空");
        }
        Account tar = null;
        for (int i = 0; i < list.size(); i++) {
            if(id.equals(list.get(i).getId())) {
                tar = list.get(i);
                break;
            }
        }
        tar.setUsername(account.getUsername());
        tar.setPassword(account.getPassword());
        return new Result(200, "更新成功");
    }

    @RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
    public Result delete(@PathVariable Integer id) {
        Account tar = null;
        for (int i = 0; i < list.size(); i++) {
            if(id.equals(list.get(i).getId())) {
                tar = list.get(i);
                break;
            }
        }
        if(tar != null) {
            list.remove(tar);
        }
        return new Result(200, "删除成功");
    }
}
